/*
* 苏州海管家物流科技有限公司（https://www.hgj.com/）.
* 苏公网安备32059002003385号 © 2015-2022 Hgj.com All Rights Reserved. | 苏ICP备15030950号.
* @Date: 2022.03.03.
* @Author
* @Description 企点管理后台 - 数据统计 - 数据报表 模块.
**/
<template>
  <Layout>
    <section class="p-5 bg-white mb-5">
      <el-form
        ref="queryForm"
        label-width="120px"
        class="flex flex-wrap"
        :model="originQuery"
      >
        <el-form-item
          class="w-4/12"
          label="企业名称"
          prop="corpName"
        >
          <el-input v-model.trim="originQuery.corpName" />
        </el-form-item>

        <el-form-item
          class="w-4/12"
          label="销售区域"
          prop="saleArea"
        >
          <el-select
            v-model.trim="originQuery.saleArea"
            multiple
          >
            <el-option
              v-for="item in areaList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          class="w-4/12"
          label="销售类型"
          prop="saleType"
        >
          <el-select v-model.trim="originQuery.saleType">
            <el-option
              label="全部"
              :value="null"
            />
            <el-option
              label="分销"
              :value="1"
            />
            <el-option
              label="直销"
              :value="2"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          class="w-4/12"
          label="经销商"
          prop="dealerId"
        >
          <el-select
            v-model.trim="originQuery.dealerId"
            filterable
            remote
            :remote-method="remoteMethod"
          >
            <el-option
              label="全部"
              :value="null"
            />
            <el-option
              v-for="item in distributorList"
              :key="item.id"
              :label="item.dealerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          class="w-4/12"
          label="客户成功"
          prop="customerSuccess"
        >
          <el-select
            v-model.trim="originQuery.customerSuccess"
            filterable
            remote
            :remote-method="remoteMethod"
          >
            <el-option
              label="全部"
              :value="null"
            />
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.dataCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          class="w-4/12"
          label="企业标签"
          prop="tags"
        >
          <el-select
            v-model.trim="originQuery.tags"
            multiple
          >
            <el-option
              v-for="item in queryLabel"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="使用时段"
          prop="dataTime"
        >
          <el-date-picker
            v-model="originQuery.dataTime"
            type="daterange"
            align="right"
            value-format="yyyy-MM-dd"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleQuery"
          >
            查询
          </el-button>
          <el-button
            type="primary"
            :disabled="loading"
            @click="handleExport"
          >
            导出
          </el-button>
          <el-button @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div v-if="query.shippingSpaceId">
        舱位编号为{{ query.shippingSpaceId }} 的结果，点击重置以显示全部
      </div>
    </section>
    <!-- table list -->
    <section class="w-100vw">
      <el-table
        ref="table"
        :data="tableList"
        border
      >
        <el-table-column
          label="序号"
          type="index"
          width="50"
          fixed="left"
        >
          <template #default="scope">
            <span>{{ (query.num - 1) * query.size + scope.$index + 1 }}  </span>
          </template>
        </el-table-column>
        <el-table-column
          label="企业名称"
          prop="corpName"
          width="100"
          fixed="left"
        />

        <el-table-column label="企业基本信息">
          <el-table-column
            label="企业ID"
            prop="corpId"
            width="100"
          />
          <el-table-column
            label="销售区域"
            prop="saleAreaName"
            width="100"
          />
          <el-table-column
            label="销售类型"
            prop="saleTypeName"
            width="100"
          />
          <el-table-column
            label="经销商"
            prop="dealer"
            width="100"
          />
          <el-table-column
            label="客户成功"
            prop="customerSuccess"
            width="100"
          />
          <el-table-column
            label="标签"
            prop="companyTagsDetail"
            width="100"
          />
          <el-table-column
            label="备注"
            prop="remark"
            width="100"
          />
        </el-table-column>

        <el-table-column label="总体使用情况">
          <el-table-column
            label="海管家应用使用人数"
            prop="hgjUseNum"
            width="100"
          />
          <el-table-column
            label="海管家应用使用次数"
            prop="hgjUseTimes"
            width="100"
          />
          <el-table-column
            label="公司人均使用次数"
            prop="hgjUseAvg"
            width="100"
          />
        </el-table-column>

        <el-table-column label="SAAS联动">
          <el-table-column
            label="绑定用户数"
            prop="bindUserNum"
            width="100"
          />
          <el-table-column
            label="货代系统使用人数"
            prop="saasUseNum"
            width="100"
          />
          <el-table-column
            label="货代系统使用次数"
            prop="saasUseTimes"
            width="100"
          />
          <el-table-column
            label="saas订单查询人数"
            prop="saasOrderDetailNum"
            width="100"
          />
          <el-table-column
            label="saas订单查询次数"
            prop="saasOrderDetailTimes"
            width="100"
          />
          <el-table-column
            label="saas订单创建人数"
            prop="saasOrderCreateNum"
            width="100"
          />
          <el-table-column
            label="saas订单创建次数"
            prop="saasOrderCreateTimes"
            width="100"
          />
          <el-table-column
            label="saas账单查询人数"
            prop="saasBillIndexNum"
            width="100"
          />
          <el-table-column
            label="saas账单查询次数"
            prop="saasBillIndexTimes"
            width="100"
          />
          <el-table-column
            label="saas费用模板查询人数"
            prop="saasFeeTempNum"
            width="100"
          />
          <el-table-column
            label="saas费用模板查询次数"
            prop="saasFeeTempTimes"
            width="100"
          />
        </el-table-column>

        <el-table-column label="数据查询-港区查询">
          <el-table-column
            label="绑定用户数"
            prop="latboxBindUserNum"
            width="100"
          />
          <el-table-column
            label="港区查询人数"
            prop="latboxSubcribeNum"
            width="110"
          />
          <el-table-column
            label="港区查询次数"
            prop="latboxSubcribeTimes"
            width="110"
          />
        </el-table-column>

        <el-table-column label="数据查询-船舶定位">
          <el-table-column
            label="绑定用户数"
            prop="shipLocateBindUserNum"
            width="100"
          />
          <el-table-column
            label="船舶定位查询人数"
            prop="shipLocateNum"
            width="100"
          />
          <el-table-column
            label="船舶定位查询次数"
            prop="shipLocateTimes"
            width="100"
          />
        </el-table-column>

        <el-table-column label="数据查询-空运数据">
          <el-table-column
            label="空运数据查询人数"
            prop="freightNum"
            width="100"
          />
          <el-table-column
            label="空运数据查询次数"
            prop="freightTimes"
            width="100"
          />
        </el-table-column>
        
        <el-table-column label="数据查询-国际快递">
          <el-table-column
            label="国际快递查询人数"
            prop="trackingNum"
            width="100"
          />
          <el-table-column
            label="国际快递查询次数"
            prop="trackingTimes"
            width="100"
          />
        </el-table-column>
        <!-- 1、2 无 -->
        <el-table-column label="舱位交易-我的舱位">
          <el-table-column
            label="新建舱位人数"
            prop="createShippingSpaceNum"
            width="110"
          />
          <el-table-column
            label="新建舱位数"
            prop="createShippingSpaceTimes"
            width="100"
          />

          <el-table-column
            label="发布舱位人数"
            prop="publishShippingSpaceNum"
            width="110"
          />
          <el-table-column
            label="发布舱位数"
            prop="publishShippingSpaceTimes"
            width="100"
          />
        </el-table-column>

        <el-table-column label="舱位交易-现舱商机">
          <el-table-column
            label="发起沟通人数"
            prop="nlpcabinContactNum"
            width="110"
          />
          <el-table-column
            label="发起沟通次数"
            prop="nlpcabinContactTimes"
            width="110"
          />
        </el-table-column>

        <el-table-column label="舱位交易-关键词商机">
          <el-table-column
            label="关键词开启人数"
            prop="nlpEnableNum"
            width="100"
          />
          <el-table-column
            label="发起沟通人数"
            prop="nlpContactNum"
            width="110"
          />
          <el-table-column
            label="发起沟通次数"
            prop="nlpContactTimes"
            width="110"
          />
        </el-table-column>

        <el-table-column label="辅助功能-销售线索">
          <el-table-column
            label="销售线索使用人数"
            prop="saleClueNum"
            width="100"
          />
          <el-table-column
            label="销售线索使用次数"
            prop="saleClueTimes"
            width="100"
          />
        </el-table-column>

        <el-table-column label="辅助功能-客户管理">
          <el-table-column
            label="客户管理使用人数"
            prop="empCustomerNum"
            width="100"
          />
          <el-table-column
            label="客户管理使用次数"
            prop="empCustomerTimes"
            width="100"
          />
        </el-table-column>

        <el-table-column label="辅助功能-微海报">
          <el-table-column
            label="微海报使用人数"
            prop="miniCardNum"
            width="100"
          />
          <el-table-column
            label="微海报使用次数"
            prop="miniCardTimes"
            width="100"
          />
        </el-table-column>

        <el-table-column label="辅助功能-共享资料">
          <el-table-column
            label="共享资料使用人数"
            prop="shareDocNum"
            width="100"
          />
          <el-table-column
            label="共享资料使用次数"
            prop="shareDocTimes"
            width="100"
          />
        </el-table-column>

        <el-table-column label="辅助功能-常用网址">
          <el-table-column
            label="网址使用人数"
            prop="openUrlNum"
            width="80"
          />
          <el-table-column
            label="网址使用次数"
            prop="openUrlTimes"
            width="80"
          />
        </el-table-column>
      </el-table>

      <div class="text-center py-4">
        <el-pagination
          v-model:current-page="query.num"
          background
          :total="total"
          :page-size="query.size"
          @current-change="handlePageChange"
        />
      </div>
    </section>
  </Layout>
</template>

<script>
import dayjs from 'dayjs'
import { mapGetters } from 'vuex'
import Layout from '@/layout/index.vue'
import { exportAba, getReleaseCompany, pageAba} from '@/api/cabin'
import {customerSucList, getDealer, getUserTags} from '@/api/records'

export default {
    components: {
        Layout
    },
    data() {
        return {
            query: {
                num: 1,
                size: 10
            },
            originQuery: {
                tags: [], // 标签
                toDate: '', // 查询结束时间
                dealerId: '', // 经销商ID
                saleArea: [], // 销售区域
                saleType: '', // 销售类型
                dataTime: [],
                fromDate: '', // 查询开始时间
                corpName: '', // 企业名称
                customerSuccess: '' // 客户成功
            },
            tableList: [],
            harborList: [],
            companyList: [],
            companyOpts: [],
            companyOptsOrigin: [],
            total: 0,
            loading: false,
            areaList: [{ // 销售区域
                value: 1,
                label: '华东'
            }, {
                value: 2,
                label: '华南'
            }, {
                value: 3,
                label: '华北'
            }, {
                value: 4,
                label: '其余'
            }],
            labelList: [], // 标签数据
            queryLabel: [], // 全部标签 - 查询条件
            distributorList: [], // 经销商
            customerList: [], // 客户成功 数据

            minDate: '',
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date()
                        const start = new Date()
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                        picker.$emit('pick', [start, end])
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date()
                        const start = new Date()
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                        picker.$emit('pick', [start, end])
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date()
                        const start = new Date()
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                        picker.$emit('pick', [start, end])
                    }
                }],
                onPick: ({ maxDate, minDate }) => {
                    this.minDate = minDate
                    console.log('maxDate, minDate---------------', maxDate, minDate)
                },
                disabledDate: (time) => { // 查询时间跨度为31天
                    if (this.minDate) {
                        let range = 365 * 24 * 3600 * 1000
                        return time.getTime() > (this.minDate.getTime() + range) || time.getTime() < (this.minDate.getTime() - range)
                    }
                    // return time.getTime()
                }
            }
        }
    },
    computed: {
        ...mapGetters({
            cabinId: 'cabin/getCabinId'
        })
    },
    created() {
        if (this.cabinId) {
            this.query.shippingSpaceId = this.cabinId
            this.$store.dispatch('cabin/setCabinId', null)
        }

        this.getLabel()
        this.defaultDate()
        this.handleQuery() // 获取 数据列表
        this.getDistributor() // 获取经销商信息
        this.getCustomerSuccess() // 客户成功 数据
        this.getShownCompanyInfo()
    },
    methods: {
        /**
        *@Description 默认时间.
        *@Return .
       **/
        defaultDate() {
            const start = dayjs().format('YYYY-MM-DD')
            const end = dayjs(new Date().getTime() - 3600 * 1000 * 24 * 7).format('YYYY-MM-DD')
            this.originQuery.dataTime = [end, start]
        },
        /**
        *@Description 查询所有标签.
        *@Return .
       **/
        getLabel() {
            getUserTags().then(res => {
                this.queryLabel = [...res.data]
            })
        },
        /**
       *@Description 获取客户成功 数据.
       *@Return .
       **/
        getDistributor() {
            getDealer().then(res => {
                this.distributorList = [...res.data]
            })
        },
        /**
       *@Description 获取客户成功 数据.
       *@Return .
       **/
        getCustomerSuccess() {
            customerSucList({code: 1005}).then(res => {
                this.customerList = [...res.data]
            })
        },
        /**
        *@Description 经销商 数据查询.
        *@Return .
       **/
        remoteMethod(query) {
            if (query !== '') {
                this.loading = true
                setTimeout(() => {
                    this.loading = false
                    this.options = this.list.filter(item => {
                        return item.label.toLowerCase()
                            .indexOf(query.toLowerCase()) > -1
                    })
                }, 200)
            } else {
                this.options = []
            }
        },
        /**
        *@Description 查询.
        *@Return .
       **/
        async handleQuery() {
            this.query = { ...this.query, ...this.originQuery }
            this.query.num = 1
            this.searchFunc()
        },
        async searchFunc() {
            const params = { ...this.query }
            if (this.originQuery?.dataTime) {
                params.toDate = this.originQuery.dataTime[1] // 查询结束时间
                params.fromDate = this.originQuery.dataTime[0] // 查询开始时间
            } else {
                const start = dayjs().format('YYYY-MM-DD')
                const end = dayjs(new Date().getTime() - 3600 * 1000 * 24 * 365).format('YYYY-MM-DD')

                params.toDate = end // 查询结束时间
                params.fromDate = start // 查询开始时间
            }

            delete params.dataTime

            let res = await pageAba(params)
            this.total = res.data.total
            this.tableList = res.data.records
        },
        /**
        *@Description 重置.
        *@Return .
       **/
        handleReset() {
            this.query = {
                num: 1,
                size: 10
            }
            this.originQuery = {}
            this.handleQuery()
        },
        /**
         *@Description 导出.
         *@Return .
         **/
        async handleExport() {

            if (!this.query.dataTime) {
                return this.$message.warning('导出必须选择一段时间')
            }

            const params = { ...this.query, ...this.originQuery }

            if (this.originQuery?.dataTime) {
                params.toDate = this.originQuery.dataTime[1] // 查询结束时间
                params.fromDate = this.originQuery.dataTime[0] // 查询开始时间
            } else {
                const start = dayjs().format('YYYY-MM-DD')
                const end = dayjs(new Date().getTime() - 3600 * 1000 * 24 * 365).format('YYYY-MM-DD')

                params.toDate = end // 查询结束时间
                params.fromDate = start // 查询开始时间
            }

            delete params.dataTime
          
            try {
                this.loading = true
                let res = await exportAba(params)

                const url = window.URL.createObjectURL(
                    new Blob([res], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    })
                )
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', `数据报表_${dayjs().format('YYYY-MM-DD_HH_mm_ss')}.xlsx`)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            } catch (e) {
                console.log('导出异常：', e)
            } finally {
                this.loading = false
            }
        },
        async getShownCompanyInfo() {
            let res = await getReleaseCompany({ isPublished: true })
            this.companyOptsOrigin = res.data
            this.companyOpts = res.data.slice(0, 100)
        },
        /**
         *@Description 分页.
         *@Return .
         **/
        handlePageChange() {
            this.searchFunc()
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table thead.is-group th {
  background: #6e769d;
}
.w-100vw {
  width: calc(100vw - 185px);
}
</style>
